﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Util
{
    public class Tools
    {
        /// <summary>
        /// 验证激活
        /// </summary>
        /// <param name="uq"></param>
        /// <returns></returns>
        public static bool CheckReg(string uq)
        {
            var error = ReadSetting("uqkey_rval", out string rval);
            if (string.IsNullOrEmpty(error) && !string.IsNullOrEmpty(rval))
            {
                return CheckEq(uq,rval);
            }
            return false;
        }
        public static bool CheckEq(string uq,string rval)
        {
            return Sign(uq.Substring(0, 19) + uq + uq.Substring(23)) == rval;
        }
        /*写入注册表*/
        public static string WriteSetting(string key, string val)  // name = key  value=setting  Section= path
        {
            var key1 = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\MyTest_ChildPlat\\ChildPlat");
            try
            {
                key1.SetValue(key, val);
                return "";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                key1.Close();
            }
        }
        /*读取注册表*/
        static string ReadSetting(string key, out string uniquekey)
        {
            uniquekey = "";
            var key1 = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\MyTest_ChildPlat\\ChildPlat");
            if (key1 != null)
            {
                object obj1 = key1.GetValue(key, "");
                key1.Close();
                if (obj1 != null)
                {
                    if (!(obj1 is string))
                    {
                        return "reg-uk值异常";
                    }
                    uniquekey = obj1.ToString();
                    return "";
                }
                return "reg-uk读取失败";
            }
            else
            {
                return "reg-uk不存在";
            }
        }
        /// <summary>
        /// 获取软件唯一编码
        /// </summary>
        /// <returns></returns>
        public static string GetUQCode()
        {
            var error = ReadSetting("uqkey", out string uqkey);
            if (string.IsNullOrEmpty(error) && !string.IsNullOrEmpty(uqkey))
                return uqkey;
            return "";
        }
        static string Sign(string s)
        {
            var md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(s)));
            t2 = t2.Replace("-", "").ToLower();
            return t2;
        }

    }
}
